package com.asiainfo.dacp.datastash.worker.executor.adapter.datax;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.model.Constant;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.model.domain.Job;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.model.domain.JobId;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.model.domain.StepPair;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.translate.JobTranslate;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.CommonErrorCode;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.Configuration;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.WorkerException;
import com.google.common.io.Files;

/**
 * 
 * 1.根据reader／writer的类型获取不同plugin的模版parameter 
 * 2.读取映射关系配置文件（可选）获取参数映射关系
 * 3.读取通用模版，填充参数
 * 
 * @author yuqs
 *
 */
public class DataxTranslater {

	private JobTranslate capture;
	
	public DataxTranslater(JobTranslate capture){
		this.capture = capture;
	}
	
	public Job jobInfo(JobId id) {
		return capture.translate(id);
	} 
	
	public String getJsonStr(Job job){
		List<StepPair> steps = job.getSteps();
		Configuration template = buildTemplate();
		if(steps != null)
		for(StepPair pair : steps){
			template.set(Constant.DATAX_JOB_CONTENT_READER_NAME, pair.reader().getName());
			template.set(Constant.DATAX_JOB_CONTENT_READER_PARAMETER, pair.reader().getParamter());
			template.set(Constant.DATAX_JOB_CONTENT_WRITER_NAME, pair.writer().getName());
			template.set(Constant.DATAX_JOB_CONTENT_WRITER_PARAMETER, pair.writer().getParamter());
			break;
		} 
		return template.beautify();
	}

	private Configuration buildTemplate() {
		String jobResource = DataxTranslater.class.getClassLoader().getResource(".").getFile();
		jobResource = jobResource + File.separator +"datax"+ File.separator + "template.json";
		String readFileToString;
		try {
			readFileToString = Files.toString(new File(jobResource), Charset.defaultCharset());
		} catch (IOException e) {
			throw WorkerException.asDataXException(CommonErrorCode.CONFIG_ERROR, "获取作业配置信息失败:" + jobResource, e);
		}
		return Configuration.from(readFileToString);
	} 
}
